package com.h.forum.services.impl;

import com.h.forum.common.enums.ResultCode;
import com.h.forum.common.utils.StringUtil;
import com.h.forum.dao.ArticleReplyMapper;
import com.h.forum.exception.ApplicationException;
import com.h.forum.pojo.model.ArticleReply;
import com.h.forum.pojo.response.AppResult;
import com.h.forum.services.IArticleReplyService;
import com.h.forum.services.IArticleService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class ArticleReplyServiceImpl implements IArticleReplyService {

    @Resource
    private ArticleReplyMapper articleReplyMapper;

    @Resource
    private IArticleService articleService;

    /**
     * 创建一个回复信息
     * @param articleReply
     */
    @Override
    public void create(ArticleReply articleReply) {
        // 非空校验
        if (articleReply == null
                || articleReply.getArticleId() == null
                || articleReply.getPostUserId() == null
                || StringUtil.isEmpty(articleReply.getContent())) {
            // 存在问题
            // 打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        // 初始化
        articleReply.setReplyId(null);
        articleReply.setReplyUserId(null);
        articleReply.setLikeCount(0);
        articleReply.setState((byte) 0);
        articleReply.setDeleteState((byte) 0);
        Date date = new Date();
        articleReply.setCreateTime(date);
        articleReply.setUpdateTime(date);

        // 调用DAO层
        int row = articleReplyMapper.insertSelective(articleReply);
        if (row != 1) {
            // 打印日志
            log.warn(ResultCode.ERROR_SERVICES.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.ERROR_SERVICES));
        }
        // 创建成功，进行增加这个帖子的回复数
        articleService.addOneReplyCountById(articleReply.getArticleId());


    }

    /**
     * 查询回复列表根据 帖子的Id
     * @param articleId
     * @return
     */
    @Override
    public List<ArticleReply> selectByArticleId(Long articleId) {
        // 校验
        if (articleId == null
                || articleId <= 0) {
            // 打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        // 调用DAO层
        List<ArticleReply> articleReplies = articleReplyMapper.selectByArticleId(articleId);
        return articleReplies;
    }
}
